package com.genesis.yunnanji.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.genesis.yunnanji.Constants;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.bean.BaseBean;
import com.genesis.yunnanji.bean.LoginBean;
import com.genesis.yunnanji.bean.MessageBean;
import com.genesis.yunnanji.bean.MessageEventBean;
import com.genesis.yunnanji.bean.WXUserInfoBean;
import com.genesis.yunnanji.utils.ImageUtil;
import com.genesis.yunnanji.utils.NetUtils;
import com.genesis.yunnanji.utils.PhoneUtil;
import com.genesis.yunnanji.utils.RegexUtils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.youth.xframe.utils.XEncryptUtils;
import com.youth.xframe.utils.log.XLog;
import com.youth.xframe.widget.XStateButton;
import com.youth.xframe.widget.XToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.bining.footstone.utils.SharedUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 创建日期：2018/9/19 on 9:40
 * 作者:Kite
 * 描述: 登陆界面
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.hint_one)
    TextView hintOne;

    @BindView(R.id.hint_three)
    TextView hintThree;

    @BindView(R.id.hint_two)
    TextView hintTwo;

    @BindView(R.id.hint_four)
    TextView hintFour;

    @BindView(R.id.et_phone)
    EditText etPhone;

    @BindView(R.id.et_code)
    EditText etCode;

    @BindView(R.id.tv_get_code)
    TextView tvGetCode;

    @BindView(R.id.tv_password_login)
    TextView tvPasswordLogin;

    @BindView(R.id.tv_phone_login)
    TextView tvPhoneLogin;

    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;

    @BindView(R.id.btn_login)
    XStateButton btnLogin;

    private LinkedHashMap<Integer, String> errorMap = new LinkedHashMap<>();

    private String mEncryptionInfo;

    private int mLoginType = 0;//0手机登录，1密码登录

    private Tencent mTencent;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        super.initView();
        initActionBar();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 11101) {
            Tencent.onActivityResultData(requestCode, resultCode, data, new BaseUiListener());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void initActionBar() {
        setTitle(" ");
        setBackRes(R.drawable.login_close);
        addMenuTextItem(R.string.register, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                advance(RegisterActivity.class);
            }
        });
        new PhoneUtil().phoneEditNum(etPhone);
        editIsEmpty();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessageInfo(MessageBean messageEvent) {
        mEncryptionInfo = messageEvent.getSmstoken();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getWXInfo(WXUserInfoBean messageEvent) {
        final String openid1 = messageEvent.getOpenid();
        final String nickname = messageEvent.getNickname();
        final int sex = messageEvent.getSex();
        final String headimgurl = messageEvent.getHeadimgurl();
        Glide.with(LoginActivity.this)
                .asBitmap()
                .load(headimgurl)
                .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        String locationImg = ImageUtil.saveImageToGallery(LoginActivity.this, resource);
                        String serviceImg = Base64.encodeToString(ImageUtil.readStream(locationImg), Base64.NO_WRAP);
                        XLog.e("serviceImg========" + serviceImg);
                        if (serviceImg != null) {
                            loginToWX(openid1, nickname, sex, serviceImg, "");
                        } else {
                            loginToWX(openid1, nickname, sex, "", "");
                        }
                    }
                });
    }

    @OnClick({R.id.tv_get_code, R.id.btn_login, R.id.tv_password_login, R.id.tv_phone_login, R.id.tv_forget_password, R.id.tv_login_qq, R.id.tv_login_wx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_code:
                getCode(etPhone, tvGetCode, "login");
                break;
            case R.id.btn_login:
                if (mLoginType == 0) {
                    loginPhone();
                } else if (mLoginType == 1) {
                    loginPassword();
                }
                break;
            case R.id.tv_password_login:
                passwordLogin();
                break;
            case R.id.tv_phone_login:
                phoneLogin();
                break;
            case R.id.tv_forget_password:
                advance(ForgetPasswordActivity.class);
                break;
            case R.id.tv_login_qq:
                loginQQ();
                break;
            case R.id.tv_login_wx:
                loginWX();
                break;
        }
    }

    private void passwordLogin() {
        mLoginType = 1;
        hintOne.setVisibility(View.INVISIBLE);
        hintTwo.setVisibility(View.INVISIBLE);
        hintThree.setVisibility(View.VISIBLE);
        hintFour.setVisibility(View.VISIBLE);
        tvPasswordLogin.setVisibility(View.INVISIBLE);
        tvPhoneLogin.setVisibility(View.VISIBLE);
        tvForgetPassword.setVisibility(View.VISIBLE);
        tvGetCode.setVisibility(View.INVISIBLE);
        etCode.setHint("请输入密码");
        etCode.setText("");
        etCode.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }

    private void phoneLogin() {
        mLoginType = 0;
        hintOne.setVisibility(View.VISIBLE);
        hintTwo.setVisibility(View.VISIBLE);
        hintThree.setVisibility(View.INVISIBLE);
        hintFour.setVisibility(View.INVISIBLE);
        tvPasswordLogin.setVisibility(View.VISIBLE);
        tvPhoneLogin.setVisibility(View.INVISIBLE);
        tvForgetPassword.setVisibility(View.INVISIBLE);
        etCode.setHint("请输入验证码");
        etCode.setText("");
        tvGetCode.setVisibility(View.VISIBLE);
        etCode.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    }

    private void editIsEmpty() {
        TextWatcher etPhoneWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable != null) {
                    String mobile = editable.toString().replace(" ", "");
                    if (!TextUtils.isEmpty(mobile)) {
                        errorMap.remove(1);
                        if (mobile.length() == 11 && RegexUtils.checkMobile(mobile)) {
                            errorMap.remove(2);
                        } else {
                            errorMap.put(2, "请填写正确的手机号码");
                        }
                    } else {
                        errorMap.put(1, "请输入您的手机号码");
                    }
                    changeClickable();
                }
            }
        };
        etPhone.addTextChangedListener(etPhoneWatcher);

        TextWatcher etCodeWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable != null) {
                    String code = editable.toString();
                    if (!TextUtils.isEmpty(code)) {
                        errorMap.remove(3);
                        if (code.length() >= 4 && code.length() <= 16) {
                            errorMap.remove(4);
                        } else {
                            errorMap.put(4, "请输入正确的验证码/密码");
                        }
                    } else {
                        errorMap.put(3, "请输入验证码/密码");
                    }
                    changeClickable();
                }
            }
        };
        etCode.addTextChangedListener(etCodeWatcher);
        errorMap.put(4, "请输入您的登录密码");
        errorMap.put(1, "请输入您的手机号码");

        btnLogin.setClickable(false);
        btnLogin.setNormalBackgroundColor(getResources().getColor(R.color.color_ccc));
    }

    public void changeClickable() {
        if (errorMap.isEmpty()) {
            btnLogin.setClickable(true);
            btnLogin.setNormalBackgroundColor(getResources().getColor(R.color.colorTheme));
        } else {
            btnLogin.setClickable(false);
            btnLogin.setNormalBackgroundColor(getResources().getColor(R.color.color_ccc));
        }
    }

    //region QQ登录

    private String openidString;

    private void loginQQ() {
        mTencent = Tencent.createInstance(Constants.QQ_APPID, getApplicationContext());
        mTencent.login(this, "all", new BaseUiListener());
    }

    class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(final Object response) {

            XLog.e("QQ登录回调:" + response.toString());

            /**
             * 下面隐藏的是用户登录成功后 登录用户数据的获取的方法
             * 共分为两种  一种是简单的信息的获取,另一种是通过UserInfo类获取用户较为详细的信息
             *有需要看看
             * */
            try {
                //获得的数据是JSON格式的，获得你想获得的内容
                //如果你不知道你能获得什么，看一下下面的LOG
                Log.v("----TAG--", "-------------" + response.toString());
                openidString = ((JSONObject) response).getString("openid");
                mTencent.setOpenId(openidString);
                mTencent.setAccessToken(((JSONObject) response).getString("access_token"), ((JSONObject) response).getString("expires_in"));

                Log.v("TAG", "-------------" + openidString);
                //access_token= ((JSONObject) response).getString("access_token");
                //expires_in = ((JSONObject) response).getString("expires_in");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /**到此已经获得OpneID以及其他你想获得的内容了
             QQ登录成功了，我们还想获取一些QQ的基本信息，比如昵称，头像什么的，这个时候怎么办？
             sdk给我们提供了一个类UserInfo，这个类中封装了QQ用户的一些信息，我么可以通过这个类拿到这些信息
             如何得到这个UserInfo类呢？  */

            QQToken qqToken = mTencent.getQQToken();
            UserInfo info = new UserInfo(getApplicationContext(), qqToken);

            //info.getUserInfo(new BaseUIListener(this,"get_simple_userinfo"));
            info.getUserInfo(new IUiListener() {
                @Override
                public void onComplete(Object o) {
                    //用户信息获取到了
                    try {
                        int gender = 0;
                        if (((JSONObject) o).getString("gender") == "男") {
                            gender = 1;
                        } else if (((JSONObject) o).getString("gender") == "女") {
                            gender = 2;
                        }
                        loginToQQ(response.toString(), ((JSONObject) o).getString("nickname"), gender, ((JSONObject) o).getString("figureurl"), "");
                        finish();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(UiError uiError) {
                    Log.v("UserInfo", "onError");
                }

                @Override
                public void onCancel() {
                    Log.v("UserInfo", "onCancel");
                }
            });

        }

        @Override
        public void onError(UiError uiError) {
            XToast.error("QQ登录出现错误");
        }

        @Override
        public void onCancel() {
            XToast.info("QQ登录已取消");
        }

    }

    private void loginToQQ(String openid, String nickname, int sex, String photo, String birthday) {
        JSONObject params = new JSONObject();
        try {
            params.put("openid", openid);
            params.put("nickname", nickname);
            params.put("sex", sex);
            params.put("photo", photo);
            params.put("birthday", birthday);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.LOGIN_QQCONNECT)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<LoginBean>, LoginBean>(new SimpleCallBack<LoginBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(LoginBean bean) {
                        XToast.success("登录成功！");
                        SharedUtils.put(Constants.USERISLOGIN, true);
                        SharedUtils.put(Constants.USER_TOKEN, bean.getApptoken());
                        EventBus.getDefault().post(new MessageEventBean(true));
                        advance(HomePageActivity.class);
                    }
                }) {
                });
    }

    //endregion

    //region 微信登录

    private void loginWX() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constants.WEIXIN_APPID, true);
        // 将该app注册到微信
        api.registerApp(Constants.WEIXIN_APPID);

        //发起登录请求
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_CYB";
        api.sendReq(req);
    }

    public void loginToWX(String openid, String nickname, int sex, String photo, String birthday) {

        JSONObject params = new JSONObject();
        try {
            params.put("openid", openid);
            params.put("nickname", nickname);
            params.put("sex", sex);
            params.put("photo", photo);
            params.put("birthday", birthday);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.LOGIN_WXOPENCONNECT)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<LoginBean>, LoginBean>(new SimpleCallBack<LoginBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(LoginBean bean) {
                        XToast.success("登录成功！");
                        SharedUtils.put(Constants.USERISLOGIN, true);
                        SharedUtils.put(Constants.USER_TOKEN, bean.getApptoken());
                        EventBus.getDefault().post(new MessageEventBean(true));
                        advance(HomePageActivity.class);
                    }
                }) {
                });
    }

    //endregion

    private void loginPhone() {
        JSONObject params = new JSONObject();
        try {
            String phoneNumber = etPhone.getText().toString().trim().replaceAll(" ", "");
            params.put("mobile", phoneNumber);
            params.put("mcode", etCode.getText().toString());
            params.put("smstoken", mEncryptionInfo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.LOGIN_MOBILE)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<LoginBean>, LoginBean>(new SimpleCallBack<LoginBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(LoginBean bean) {
                        SharedUtils.put(Constants.USERISLOGIN, true);
                        SharedUtils.put(Constants.USER_TOKEN, bean.getApptoken());
                        EventBus.getDefault().post(new MessageEventBean(true));
                        advance(HomePageActivity.class);
                    }
                }) {
                });
    }

    private void loginPassword() {
        JSONObject params = new JSONObject();
        String md5Password = XEncryptUtils.MD5("jzwhcb" + XEncryptUtils.MD5(etCode.getText().toString()));
        try {
            String phoneNumber = etPhone.getText().toString().trim().replaceAll(" ", "");
            params.put("uname", phoneNumber);
            params.put("upwd", md5Password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.LOGIN_UNAME)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<LoginBean>, LoginBean>(new SimpleCallBack<LoginBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(LoginBean bean) {
                        SharedUtils.put(Constants.USERISLOGIN, true);
                        SharedUtils.put(Constants.USER_TOKEN, bean.getApptoken());
                        EventBus.getDefault().post(new MessageEventBean(true));
                        advance(HomePageActivity.class);
                    }
                }) {
                });
    }

}
